<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';

import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from 'ant-design-vue';

const props = defineProps<Props>();

const { Title, Text } = Typography;

interface Alert {
  id: string;
  deviceId: string;
  deviceName: string;
  type: 'critical' | 'info' | 'warning';
  status: 'acknowledged' | 'active' | 'resolved';
  message: string;
  timestamp: string;
  acknowledgedBy?: string;
  acknowledgedAt?: string;
  resolvedBy?: string;
  resolvedAt?: string;
}

interface Props {
  deviceId?: string;
}

// 告警数据
const alerts = ref<Alert[]>([
  {
    id: '1',
    deviceId: 'DEV001',
    deviceName: '温湿度传感器-101',
    type: 'warning',
    status: 'active',
    message: '温度超出正常范围',
    timestamp: '2024-01-19 15:30:00',
  },
  {
    id: '2',
    deviceId: 'DEV002',
    deviceName: '烟雾传感器-大厅',
    type: 'critical',
    status: 'active',
    message: '检测到烟雾浓度异常',
    timestamp: '2024-01-19 15:25:00',
  },
  {
    id: '3',
    deviceId: 'DEV003',
    deviceName: '门锁-102',
    type: 'warning',
    status: 'acknowledged',
    message: '电池电量低',
    timestamp: '2024-01-19 15:20:00',
    acknowledgedBy: '管理员',
    acknowledgedAt: '2024-01-19 15:22:00',
  },
  {
    id: '4',
    deviceId: 'DEV004',
    deviceName: '摄像头-餐厅',
    type: 'info',
    status: 'resolved',
    message: '网络连接恢复',
    timestamp: '2024-01-19 15:15:00',
    resolvedBy: '系统',
    resolvedAt: '2024-01-19 15:18:00',
  },
]);

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  deviceName: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 获取告警类型颜色
const getAlertTypeColor = (type: string) => {
  const colors = {
    critical: 'red',
    warning: 'orange',
    info: 'blue',
  };
  return colors[type] || 'default';
};

// 获取告警类型文本
const getAlertTypeText = (type: string) => {
  const texts = {
    critical: '严重',
    warning: '警告',
    info: '信息',
  };
  return texts[type] || type;
};

// 获取告警状态颜色
const getAlertStatusColor = (status: string) => {
  const colors = {
    active: 'red',
    acknowledged: 'orange',
    resolved: 'green',
  };
  return colors[status] || 'default';
};

// 获取告警状态文本
const getAlertStatusText = (status: string) => {
  const texts = {
    active: '活跃',
    acknowledged: '已确认',
    resolved: '已解决',
  };
  return texts[status] || status;
};

// 表格列定义
const columns = [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    key: 'deviceName',
    width: 150,
  },
  {
    title: '告警类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '告警状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '告警信息',
    dataIndex: 'message',
    key: 'message',
    width: 200,
  },
  {
    title: '告警时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 150,
  },
  {
    title: '确认人',
    dataIndex: 'acknowledgedBy',
    key: 'acknowledgedBy',
    width: 100,
  },
  {
    title: '解决人',
    dataIndex: 'resolvedBy',
    key: 'resolvedBy',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const,
  },
];

// 过滤后的数据
const filteredAlerts = computed(() => {
  let result = alerts.value;

  if (props.deviceId) {
    result = result.filter((alert) => alert.deviceId === props.deviceId);
  }

  if (searchForm.type) {
    result = result.filter((alert) => alert.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((alert) => alert.status === searchForm.status);
  }

  if (searchForm.deviceName) {
    result = result.filter((alert) =>
      alert.deviceName
        .toLowerCase()
        .includes(searchForm.deviceName.toLowerCase()),
    );
  }

  return result;
});

// 告警统计
const alertStatistics = computed(() => {
  const total = alerts.value.length;
  const critical = alerts.value.filter((a) => a.type === 'critical').length;
  const warning = alerts.value.filter((a) => a.type === 'warning').length;
  const info = alerts.value.filter((a) => a.type === 'info').length;
  const active = alerts.value.filter((a) => a.status === 'active').length;
  const acknowledged = alerts.value.filter(
    (a) => a.status === 'acknowledged',
  ).length;
  const resolved = alerts.value.filter((a) => a.status === 'resolved').length;

  return {
    total,
    critical,
    warning,
    info,
    active,
    acknowledged,
    resolved,
  };
});

// 查看告警详情
const viewAlert = (record: Alert) => {
  Modal.info({
    title: '告警详情',
    width: 600,
    content: `
      <div>
        <p><strong>设备名称：</strong>${record.deviceName}</p>
        <p><strong>告警类型：</strong>${getAlertTypeText(record.type)}</p>
        <p><strong>告警状态：</strong>${getAlertStatusText(record.status)}</p>
        <p><strong>告警信息：</strong>${record.message}</p>
        <p><strong>告警时间：</strong>${record.timestamp}</p>
        ${record.acknowledgedBy ? `<p><strong>确认人：</strong>${record.acknowledgedBy} (${record.acknowledgedAt})</p>` : ''}
        ${record.resolvedBy ? `<p><strong>解决人：</strong>${record.resolvedBy} (${record.resolvedAt})</p>` : ''}
      </div>
    `,
  });
};

// 确认告警
const acknowledgeAlert = (record: Alert) => {
  Modal.confirm({
    title: '确认告警',
    content: `确定要确认告警 "${record.message}" 吗？`,
    onOk: () => {
      const index = alerts.value.findIndex((a) => a.id === record.id);
      if (index !== -1) {
        alerts.value[index].status = 'acknowledged';
        alerts.value[index].acknowledgedBy = '当前用户';
        alerts.value[index].acknowledgedAt = new Date().toLocaleString();
        message.success('告警已确认');
      }
    },
  });
};

// 解决告警
const resolveAlert = (record: Alert) => {
  Modal.confirm({
    title: '解决告警',
    content: `确定要解决告警 "${record.message}" 吗？`,
    onOk: () => {
      const index = alerts.value.findIndex((a) => a.id === record.id);
      if (index !== -1) {
        alerts.value[index].status = 'resolved';
        alerts.value[index].resolvedBy = '当前用户';
        alerts.value[index].resolvedAt = new Date().toLocaleString();
        message.success('告警已解决');
      }
    },
  });
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    type: '',
    status: '',
    deviceName: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

onMounted(() => {
  pagination.total = filteredAlerts.value.length;
});
</script>

<template>
  <div class="alert-management">
    <!-- 统计信息 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number total">{{ alertStatistics.total }}</div>
            <div class="stat-label">告警总数</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number critical">
              {{ alertStatistics.critical }}
            </div>
            <div class="stat-label">严重告警</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number warning">{{ alertStatistics.warning }}</div>
            <div class="stat-label">警告告警</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number info">{{ alertStatistics.info }}</div>
            <div class="stat-label">信息告警</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number active">{{ alertStatistics.active }}</div>
            <div class="stat-label">活跃告警</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number acknowledged">
              {{ alertStatistics.acknowledged }}
            </div>
            <div class="stat-label">已确认</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number resolved">
              {{ alertStatistics.resolved }}
            </div>
            <div class="stat-label">已解决</div>
          </div>
        </Card>
      </Col>
      <Col :span="3">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{
                alertStatistics.total > 0
                  ? Math.round(
                      (alertStatistics.resolved / alertStatistics.total) * 100,
                    )
                  : 0
              }}%
            </div>
            <div class="stat-label">解决率</div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <Form.Item label="告警类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择类型"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="critical">严重</Select.Option>
            <Select.Option value="warning">警告</Select.Option>
            <Select.Option value="info">信息</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="告警状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="active">活跃</Select.Option>
            <Select.Option value="acknowledged">已确认</Select.Option>
            <Select.Option value="resolved">已解决</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="设备名称">
          <Input
            v-model:value="searchForm.deviceName"
            placeholder="请输入设备名称"
            allow-clear
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch"> 搜索 </Button>
            <Button @click="handleReset"> 重置 </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>

    <!-- 告警列表 -->
    <Card title="告警列表" class="list-card">
      <Table
        :columns="columns"
        :data-source="filteredAlerts"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <Tag :color="getAlertTypeColor(record.type)">
              {{ getAlertTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getAlertStatusColor(record.status)">
              {{ getAlertStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewAlert(record)">
                查看
              </Button>
              <Button
                v-if="record.status === 'active'"
                type="link"
                size="small"
                @click="acknowledgeAlert(record)"
              >
                确认
              </Button>
              <Button
                v-if="record.status === 'acknowledged'"
                type="link"
                size="small"
                @click="resolveAlert(record)"
              >
                解决
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.alert-management {
  padding: 16px;
}

.statistics-row {
  margin-bottom: 16px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 12px;
}

.stat-number {
  margin-bottom: 4px;
  font-size: 20px;
  font-weight: bold;
}

.stat-number.total {
  color: #1890ff;
}

.stat-number.critical {
  color: #f5222d;
}

.stat-number.warning {
  color: #faad14;
}

.stat-number.info {
  color: #1890ff;
}

.stat-number.active {
  color: #f5222d;
}

.stat-number.acknowledged {
  color: #faad14;
}

.stat-number.resolved {
  color: #52c41a;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  background: white;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
